<?php

$uid = $_G['uid'];
$user = getuserbyuid($uid);
if(empty($user)) {
    showmessage('用户信息获取失败', '', array(), array('showdialog' => true, 'locationtime' => 3));
    exit;
}

$table_er_kami_buy_config = C::t('#erling_kami_buy#er_kami_buy_config');
$table_er_kami_buy = C::t('#erling_kami_buy#er_kami_buy');
$table_er_kami_buy_type = C::t('#erling_kami_buy#er_kami_buy_type');
$table_er_kami_buy_type_list = ($table_er_kami_buy_type->fetch_all())['data'];


$er_kami_buy_config = $table_er_kami_buy_config->fetch_by_keys([
    'allowed_groups','precautions', 'nav_name', 'recharge_url',
    'kami_api','kami_api_url','kami_api_site_credit','kami_api_get_url','kami_api_private_key'
]);
$er_kami_buy_config['recharge_url']['value']??= 'home.php?mod=spacecp&ac=credit&op=buy';
$allowed_groups = dunserialize($er_kami_buy_config['allowed_groups']['value']);
// 获取用户所有用户组(主用户组+扩展用户组)
$user_groups = array($user['groupid']);
if(!empty($user['extgroupids'])) {
    $extgroups = explode("\t", trim($user['extgroupids'], "\t"));
    $user_groups = array_merge($user_groups, $extgroups);
}
$has_permission = false;
foreach($user_groups as $group) {
    if(in_array($group, $allowed_groups)) {
        $has_permission = true;
        break;
    }
}

if(!$has_permission) {
    showmessage('您的用户组无法访问', '', array(), array('showdialog' => true, 'locationtime' => 3));
    exit;
}

// 积分类型
$extcredits_array = DB::fetch_all("SELECT * FROM %t WHERE skey LIKE %s", array('common_setting', 'extcredits%'));
if ($extcredits_array && isset($extcredits_array[0]['svalue'])) {
    $extcredits_data = unserialize($extcredits_array[0]['svalue']);
} else {
    $extcredits_data = [];
}
$extcredits_data_json = json_encode($extcredits_data);


if($_GET['buy_kami']) {
    if(!submitcheck('formhash')) {
        $data = [
            'success' => false,
            'message' => '请求来源验证失败'
        ];
        echo json_encode($data);
        exit;
    }
    if(!empty($_POST['er_api']) && $_POST['er_api'] == 'api') {
        // 第三方接口
        $kamiApiGetUrl = $er_kami_buy_config['kami_api_get_url']['value'];
        $kamiApiSiteCredit = $er_kami_buy_config['kami_api_site_credit']['value'];
        $kamiTypeId = $_POST['kami_type'];
        // 验证用户积分余额是否足够扣除,$kamiApiSiteCredit = json的[{"id":5,"name":"测试支付","extcredits":"3","credit":"1"},{"id":4,"name":"测试","extcredits":"2","credit":"2"},{"id":2,"name":"123","extcredits":"1","credit":"0"}]id为$kamiTypeId
        $kamiApiSiteCredit = json_decode($kamiApiSiteCredit, true);
        $credit = null;
        $extcredits = null;
        foreach($kamiApiSiteCredit as $item) {
            if($item['id'] == $kamiTypeId) {
                $credit = $item['credit'];
                $extcredits = $item['extcredits'];
                break;
            }
        }
        if($credit === null) {
            $data = [
                'success' => false,
                'message' => '未找到对应的积分类型配置'
            ];
            echo json_encode($data);
            exit;
        }
        $userCredit = getuserprofile('extcredits'.$extcredits, $uid);
        if($userCredit < $credit) {
            $data = [
               'success' => false,
               'message' => '您的'.$extcredits_data[$extcredits]['title'].'不足，需要'.$credit
            ];
            echo json_encode($data);
            exit;
        }

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $kamiApiGetUrl);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, [
            'id' => $kamiTypeId
        ]);
        $origin = $_SERVER['HTTP_ORIGIN'] ?? '';
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Origin: ' . $origin,
            'Accept: application/json',
        ]);
        $response = curl_exec($ch);
        $data = json_decode($response, true);
        if($data['code'] == 200) {
            $kami_data = $data['data'];
            // 解密
            $privateKey = $table_er_kami_buy_config->fetch_by_keys(['kami_api_private_key']);
            $privateKey = $privateKey['kami_api_private_key']['value'];
            openssl_private_decrypt(base64_decode($kami_data), $decrypted, $privateKey);
            $kami_data = json_decode($decrypted, true);
            
            // 记录订单
            $table_er_kami_buyforapi = C::t('#erling_kami_buy#er_kami_buyforapi');
            $table_er_kami_buyforapi->insert([
                'uid' => $uid,
                'title' => $kami_data['name'],
                'desc' => $kami_data['desc'],
                'kami_key' => $kami_data['key'],
                'order_no' => $kami_data['order_no'],
                'extcredits' => $extcredits,
                'credit' => $credit,
                'create_time' => TIMESTAMP,
                'update_time' => TIMESTAMP,
                'expire_time' => is_numeric($kami_data['exchange_expire_time']) ? 
                    (int)$kami_data['exchange_expire_time'] : 
                    strtotime($kami_data['exchange_expire_time']),
            ]);

            // 积分扣除
            updatemembercount($uid, $dataarr = array($extcredits => -$credit), $checkgroup = true, $operation = '', $relatedid = 0, $ruletxt = '');

            $data = [
                'success' => true,
                'message' => '获取成功',
                'kami_key' => $kami_data['key'],
                'kami_buy_type' => $kami_data['name'],
            ];
            
        } else {
            $data = [
               'success' => false,
               'message' => $data['msg']
            ];
        }
        
        echo json_encode($data);
        exit;
    }


    $kamiTypeId = $_POST['kami_type'];
    $kami_buy_type = $table_er_kami_buy_type->fetch($kamiTypeId);
    
    // 验证用户积分余额是否足够扣除
    $userCredit = getuserprofile('extcredits'.$kami_buy_type['extcredits'], $uid);
    if($userCredit < $kami_buy_type['credit']) {
        $data = [
            'success' => false,
            'message' => '您的'.$extcredits_data[$kami_buy_type['extcredits']]['title'].'不足，需要'.$kami_buy_type['credit']
        ];
        echo json_encode($data);
        exit;
    }
    

    // 获取卡密
    $kami = $table_er_kami_buy->buy_kami_by_type_id($kamiTypeId, $uid, $kami_buy_type['extcredits'], $kami_buy_type['credit']);
    if(!$kami) {
        $data = [
            'success' => false,
            'message' => '获取失败或无剩余卡密'
        ];
    } else {
        $data = [
            'success' => true,
            'message' => '获取成功',
            'kami_key' => $kami['kami_key'],
            'kami_buy_type' => $kami_buy_type['name'],
        ];
        // 积分扣除
        updatemembercount($uid, $dataarr = array($kami_buy_type['extcredits'] => -$kami_buy_type['credit']), $checkgroup = true, $operation = '', $relatedid = 0, $ruletxt = '');
    }
    echo json_encode($data);
    exit;
}

// 获取当前用户所有积分
$credits = DB::fetch_first("SELECT * FROM %t WHERE uid=%d", array('common_member_count', $uid));
$credits = [
    'extcredits1' => [
        'value' => $credits['extcredits1'],
        'title' => $extcredits_data[1]['title']
    ],
    'extcredits2' => [
        'value' => $credits['extcredits2'],
        'title' => $extcredits_data[2]['title']
    ],
    'extcredits3' => [
        'value' => $credits['extcredits3'],
        'title' => $extcredits_data[3]['title']
    ],
    'extcredits4' => [
        'value' => $credits['extcredits4'],
        'title' => $extcredits_data[4]['title']
    ],
    'extcredits5' => [
        'value' => $credits['extcredits5'],
        'title' => $extcredits_data[5]['title']
    ],
    'extcredits6' => [
        'value' => $credits['extcredits6'],
        'title' => $extcredits_data[6]['title']
    ],
    'extcredits7' => [
        'value' => $credits['extcredits7'],
        'title' => $extcredits_data[7]['title']
    ],
    'extcredits8' => [
        'value' => $credits['extcredits8'],
        'title' => $extcredits_data[8]['title']
    ]
];

// // 获取远程卡密
// if($er_kami_buy_config['kami_api']['value'] == 1){
//     $kami_api_url = $er_kami_buy_config['kami_api_url']['value'];//api卡密分类列表获取地址
//     $kami_api_site_credit = $er_kami_buy_config['kami_api_site_credit']['value'];//api积分购买规则
//     $kami_api_get_url = $er_kami_buy_config['kami_api_get_url']['value'];// api卡密获取地址
// }

include template('erling_kami_buy:user_kami_exchange');